import 'package:boss/color_constant.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/shadow_radius_card.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

//附带钱数设置
class BaseMoneyTextFormField extends StatefulWidget {
  final String prefixText;
  final String hintText;
  final bool isRequired;
  final TextEditingController controller;
  final String initialValue;
  final ValueChanged<String> onChanged;
  final VoidCallback onEditingComplete;
  final List<TextInputFormatter> inputFormatters;
  final bool enabled;
  final TextInputType keyboardType;
  final String suffixText;
  final Widget suffix;
  final int maxLength;
  final int maxLines;
  final FocusNode focusNode;
  final FormFieldValidator<String> validator;
  final TextAlign textAlign;
  final double horizontalPadding;
  final bool obscureText;
  final bool isClearAll;
  final List<String> actions;
  final ValueChanged<int> onActionsTap;
  final bool moneyPattern;

  const BaseMoneyTextFormField({
    Key key,
    this.prefixText,
    this.hintText,
    this.isRequired = false,
    this.controller,
    this.onChanged,
    this.onEditingComplete,
    this.initialValue,
    this.inputFormatters,
    this.enabled,
    this.keyboardType,
    this.suffixText,
    this.suffix,
    this.maxLength,
    this.focusNode,
    this.validator,
    this.maxLines = 1,
    this.textAlign = TextAlign.end,
    this.horizontalPadding,
    this.obscureText = false,
    this.isClearAll = false,
    this.actions,
    this.onActionsTap,
    this.moneyPattern,
  }) : super(key: key);

  @override
  _BaseTextFormFieldState createState() => _BaseTextFormFieldState();
}

class _BaseTextFormFieldState extends State<BaseMoneyTextFormField> {
  TextEditingController _controller;

  String get value => _controller == null ? widget.controller.text : _controller.text;

  TextEditingController get controller => _controller ?? widget.controller;

  FocusNode _focusNode;

  FocusNode get focusNode => _focusNode ?? widget.focusNode;

  String _errText;

  bool get _hasErr => _errText != null;

  OverlayEntry _entry;

  @override
  void initState() {
    super.initState();

    if (widget.controller == null) {
      _controller = TextEditingController(text: widget.initialValue);
      _controller.addListener(_handleChange);
    } else {
      widget.controller.addListener(_handleChange);
    }

    if (widget.focusNode == null) {
      _focusNode = FocusNode();

      _focusNode.addListener(_handleFocus);
    } else {
      widget.focusNode.addListener(_handleFocus);
    }
  }

  @override
  void dispose() {
    _disposeActions();

    _controller?.removeListener(_handleChange);
    _controller?.dispose();
    _controller = null;

    widget.controller?.removeListener(_handleChange);

    _focusNode?.removeListener(_handleFocus);
    _focusNode?.dispose();
    _focusNode = null;

    super.dispose();
  }

  _handleChange() {
    if (widget.maxLength != null && value.length > widget.maxLength) {
      var text = controller.text.substring(0, widget.maxLength);
      _setValue(text);
    } else {
      if (widget.onChanged != null) {
        if (widget.moneyPattern == true) {
          if (controller.text == '.') {
            controller.text = '';
          }
          if (controller.text.split(".").length > 2) {
            controller.text = controller.text.split(".")[0] + '.' + controller.text.split(".")[1];
          }
          if (controller.text.split(".").length == 2) {
            if (controller.text.split(".")[1].length > 2) {
              controller.text = controller.text.split(".")[0] + '.' + (controller.text.split(".")[1]).substring(0, 2);
            }
          }
        }
        widget.onChanged(controller.text);
      }
    }
  }

  _setValue(String text) {
    controller.text = text;
    controller.selection = TextSelection.collapsed(offset: text.length);

    if (widget.onChanged != null) {
      widget.onChanged(text);
    }
  }

  _handleFocus() {
    if (!focusNode.hasFocus) {
      _disposeActions();
      _handleValidator();
    } else {
      _handleActions();
    }
  }

  _handleActions() {
    if (widget.actions != null && widget.actions.length > 0) {
      _entry = OverlayEntry(builder: (context) {
        return Positioned(
          bottom: MediaQuery.of(context).viewInsets.bottom,
          left: 0,
          right: 0,
          child: Material(
            child: Container(
              height: 80.w,
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [DEFAULT_SHADOW],
              ),
              child: Row(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 15.w,
                    ),
                    child: Text(
                      '推荐：',
                      style: TextStyleConstant().normal_1_28,
                    ),
                  ),
                  Expanded(
                    child: ListView.builder(
                      physics: BouncingScrollPhysics(),
                      scrollDirection: Axis.horizontal,
                      itemBuilder: (context, index) {
                        var current = widget.actions[index];

                        return GestureDetector(
                          onTap: () {
                            controller.text = current;
                            controller.selection = TextSelection.collapsed(
                              offset: controller.text.length,
                            );

                            if (widget.onChanged != null) {
                              widget.onChanged(controller.text);
                            }

                            if (widget.onActionsTap != null) {
                              widget.onActionsTap(index);
                            }
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 15.w,
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              current,
                              style: TextStyleConstant().origin_28,
                            ),
                          ),
                        );
                      },
                      itemCount: widget.actions.length,
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      });

      Overlay.of(context).insert(_entry);
    }
  }

  _disposeActions() {
    if (_entry != null) {
      _entry.remove();
      _entry = null;
    }
  }

  _handleValidator() {
    if (widget.validator != null) {
      var result = widget.validator(value);

      setState(() {
        _errText = result;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> children = [];

    children.add(TextFormField(
      keyboardAppearance: Brightness.light,
      maxLines: widget.maxLines,
      focusNode: focusNode,
      textAlign: widget.textAlign,
      controller: controller,
      onEditingComplete: widget.onEditingComplete,
      inputFormatters: widget.inputFormatters,
      enabled: widget.enabled,
      keyboardType: widget.keyboardType,
      decoration: InputDecoration(
        contentPadding: EdgeInsets.symmetric(
          vertical: 35.w,
          horizontal: (widget.suffixText == null && widget.suffix == null) ? 0 : widget.horizontalPadding ?? 10.w,
        ),
        border: NoInputBorder(),
        prefix: widget.prefixText != null
            ? Text(
                widget.prefixText,
                style: TextStyle(
                  fontSize: 28.sp,
                  color: Colors.transparent,
                ),
              )
            : null,
        prefixStyle: TextStyle(
          fontSize: 28.sp,
          color: Colors.transparent,
        ),
        suffixText: widget.suffixText,
        suffixStyle: TextStyle(color: Colors.transparent),
        hintText: widget.hintText,
        hintStyle: TextStyleConstant().normal_4_28,
      ),
      style: TextStyleConstant().normal_1_28,
      obscureText: widget.obscureText,
      onTap: () {
        if (!focusNode.hasFocus) {
          controller.selection = TextSelection.collapsed(
            offset: controller.text.length,
          );
        }
      },
    ));

    if (widget.prefixText != null) {
      List<Widget> prefixChildren = [];
      prefixChildren.add(
        Text(
          widget.prefixText,
          style: TextStyleConstant().normal_1_28,
        ),
      );

      if (widget.isRequired) {
        prefixChildren.add(
          Text(
            '*',
            style: TextStyleConstant().origin_28,
          ),
        );
      }

      children.add(Positioned(
        top: 0,
        left: 0,
        bottom: 0,
        child: Container(
          child: Row(
            children: prefixChildren,
          ),
        ),
      ));
    }

    if (widget.isClearAll && value.length > 0) {
      children.add(
        Positioned(
            top: 0,
            right: 0,
            bottom: 0,
            child: Row(
              children: <Widget>[
                GestureDetector(
                  behavior: HitTestBehavior.deferToChild,
                  onTap: () {
                    controller.text = '';
                    setState(() {});
                  },
                  child: Container(
                    child: BaseImage(
                      'assets/image/form_field_clear_icon.png',
                      width: 30.w,
                      height: 30.w,
                    ),
                  ),
                ),
              ],
            )),
      );
    }

    if (widget.suffixText != null && widget.suffix == null) {
      children.add(
        Positioned(
          top: 0,
          right: 0,
          bottom: 0,
          child: Container(
            alignment: Alignment.center,
            child: Text(
              widget.suffixText,
              style: TextStyleConstant().normal_1_28,
            ),
          ),
        ),
      );
    }

    return Theme(
      data: ThemeData(
        textTheme: TextTheme(
          subtitle1: TextStyle(textBaseline: TextBaseline.alphabetic),
        ),
      ),
      child: Column(
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                bottom: BorderSide(
                  width: 1.px,
                  color: !_hasErr ? ColorConstant.e6e6 : ColorConstant.fe7f76,
                ),
              ),
            ),
            child: Row(
              textBaseline: TextBaseline.alphabetic,
              children: <Widget>[
                Expanded(
                  child: Stack(
                    children: children,
                  ),
                ),
                if (widget.suffix != null) widget.suffix,
              ],
            ),
          ),
          if (_hasErr)
            Container(
              padding: EdgeInsets.symmetric(
                vertical: 15.w,
              ),
              alignment: Alignment.centerRight,
              child: Text(
                _errText,
                style: TextStyleConstant().origin_20,
              ),
            ),
        ],
      ),
    );
  }
}
